properties { 
	$projectName = "DH.SolutionTemplate"
	$buildNumber = 0
	$rootDir  = Resolve-Path .
	$buildOutputDir = "$rootDir\build" 
	$srcDir = "$rootDir\src"
	$solutionFilePath = "$srcDir\$projectName.sln"
}

task default -depends UpdateVersionNumbers, BuildWrap

task Clean {
	Remove-Item $buildOutputDir -Force -Recurse -ErrorAction SilentlyContinue
	exec { msbuild $solutionFilePath /t:Clean }
}

task UpdateVersionNumbers {
	$assemblyInfoFilePath = "$srcDir\SharedAssemblyInfo.cs"
	$version = Get-SourceVersion $assemblyInfoFilePath
	$oldVersion = New-Object Version $version
	$newVersion = New-Object Version ($oldVersion.Major, $oldVersion.Minor, $oldVersion.Build, $buildNumber)
	Update-SourceVersion $newVersion $assemblyInfoFilePath
	
	Set-Content Version $newVersion
}

task Compile -depends Clean { 
	exec { msbuild $solutionFilePath /p:Configuration=Release }
}

task RunTests -depends Compile {
	# Xunit tools only available on internal repo, so commenting out.
	# exec { .\tools\Xunit\xunit.console.clr4.exe $src\DH.SolutionTemplate.Tests\bin\Release\DH.SolutionTemplate.Tests.dll }
}

task BuildWrap -depends Compile {
	exec { .\o.exe -ShellInstall none build-wrap }
	New-Item $buildOutputDir -type directory
	Move-Item *.wrap $buildOutputDir
}

function Update-SourceVersion
{
	param (
		[string]$version,
		[string]$assemblyInfoFilePath
		)
	
	$newVersion = 'AssemblyVersion("' + $version + '")';
	$newFileVersion = 'AssemblyFileVersion("' + $version + '")';
	$tmpFile = $assemblyInfoFilePath + ".tmp"

	Get-Content $assemblyInfoFilePath | 
		%{$_ -replace 'AssemblyVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)', $newVersion } |
		%{$_ -replace 'AssemblyFileVersion\("[0-9]+(\.([0-9]+|\*)){1,3}"\)', $newFileVersion }  > $tmpFile

	Move-Item $tmpFile $assemblyInfoFilePath -force
}

function Get-SourceVersion
{
	param
	(
		[string]$assemblyInfoFilePath
	)
	Write-Host "path $assemblyInfoFilePath"
	$pattern = '(?<=^\[assembly\: AssemblyVersion\(\")(?<versionString>\d+\.\d+\.\d+\.\d+)(?=\"\))'
	$assmblyInfoContent = Get-Content $assemblyInfoFilePath
	return $assmblyInfoContent | Select-String -Pattern $pattern | Select -expand Matches |% {$_.Groups['versionString'].Value}
}